﻿//----------------------------------------------------

#region 命名空间

//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Linq;
using WinnerCMS.Data;
using WinnerCMS.Model;
using WinnerCMS.Common;

#endregion

namespace WinnerCMS.BLL
{
    /// <summary>
    /// 业务逻辑类 WinnerCMS_Orders 的摘要说明。
    /// </summary>
    public class OrdersManage
    {
        private static readonly OrdersDal MyDAL = new OrdersDal();

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <returns></returns>
        public static string OrderNum()
        {
            return DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(10000, 99999);
        }

        #region  是否存在

        /// <summary>
        /// 是否存在
        /// </summary>
        public bool Exists(int ID)
        {
            return MyDAL.Exists(ID);
        }

        #endregion

        #region 添加

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <param name="CartGUID"></param>
        public Result Add(Order model, string CartGUID)
        {
            Result resu = new Result();
            if (model.Mobile.Length == 0 && model.Phone.Length == 0)
            {
                resu.Errors = "“电话”和“手机”不能同时为空！";
                return resu;
            }
            if (model.UserName.Length == 0)
            {
                resu.Errors = "“订购者”不能为空！";
                return resu;
            }
            if (model.ContacterName.Length == 0)
            {
                resu.Errors = "“联系人”不能为空！";
                return resu;
            }
            if (model.Address.Length == 0)
            {
                resu.Errors = "“地址”不能为空！";
                return resu;
            }

            if (model.Id == 0)
            {
                model.OrderNum = OrderNum();
                if (model.OrderNum.Length == 0)
                {
                    resu.Errors = "“订单号”不能为空！";
                    return resu;
                }

                #region 添加

                if (new ShoppingCartManage().Exists(CartGUID) == false)
                {
                    resu.Errors = "购物车为空,无法下订单。";
                    return resu;
                }

                if (CheckOutStock(CartGUID))
                {
                    resu.Errors = "订单货物超出库存。";
                    return resu;
                }

                model.Id = MyDAL.Add(model, CartGUID, 0);

                try
                {
                    resu = new OrderListManage().Add(CartGUID, model.Id, model.Remark);

                    if (string.IsNullOrEmpty(resu.Errors) == false)
                    {
                        MyDAL.Delete(model.Id.ToString());
                    }
                    else
                    {
                        new ShoppingCartManage().Clear(CartGUID);
                    }
                }
                catch (Exception ex)
                {
                    MyDAL.Delete(model.Id.ToString());

                    resu.Errors = ex.Message;
                    return resu;
                }

                #endregion
            }
            else
            {
                #region 修改

                MyDAL.Edit(model);

                #endregion
            }
            return resu;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <param name="goodsId"></param>
        public Result Add(Order model, int goodsId)
        {
            Result resu = new Result();
            if (model.Mobile.Length == 0 && model.Phone.Length == 0)
            {
                resu.Errors = "“电话”和“手机”不能同时为空！";
                return resu;
            }
            if (model.UserName.Length == 0)
            {
                resu.Errors = "“订购者”不能为空！";
                return resu;
            }
            if (model.ContacterName.Length == 0)
            {
                resu.Errors = "“联系人”不能为空！";
                return resu;
            }
            if (model.Address.Length == 0)
            {
                resu.Errors = "“地址”不能为空！";
                return resu;
            }
            model.OrderNum = OrderNum();
            if (model.OrderNum.Length == 0)
            {
                resu.Errors = "“订单号”不能为空！";
                return resu;
            }


            try
            {
                model.Id = MyDAL.Add(model, null, goodsId);

                Result res = new OrderListManage().Add(goodsId, model.Id, model.Remark);

                if (string.IsNullOrEmpty(res.Errors) == false)
                {
                    MyDAL.Delete(model.Id.ToString());

                    return resu;
                }
            }
            catch (Exception ex)
            {
                MyDAL.Delete(model.Id.ToString());

                resu.Errors = ex.Message;
                return resu;
            }
            return resu;
        }

        #endregion

        #region 删除

        /// <summary>
        /// 删除
        /// </summary>
        public void Delete(string IDs)
        {
            if (string.IsNullOrEmpty(IDs))
            {
            }
            else
            {
                MyDAL.Delete(IDs);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="IDs"></param>
        /// <param name="UpdatePanel1"></param>
        public void Delete(string IDs, UpdatePanel UpdatePanel1)
        {
            if (string.IsNullOrEmpty(IDs))
            {
                MsgBox.Message("至少选择一项。", UpdatePanel1);
            }
            else
            {
                MyDAL.Delete(IDs);
            }
        }

        #endregion

        #region 加载数据

        /// <summary>
        /// 加载数据
        /// </summary>
        public Order GetInfo(int ID)
        {
            return MyDAL.GetInfo(ID);
        }

        #endregion

        #region 绑定分页数据

        /// <summary>
        /// 绑定分页数据
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="keyWord"></param>
        /// <param name="status"></param>
        /// <param name="deliverStatus"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Order> BindList(string sort, string keyWord, string status, string deliverStatus, PagingParam pp)
        {
            return MyDAL.BindList(sort, keyWord, int.Parse(status), int.Parse(deliverStatus), pp);
        }

        #endregion

        /// <summary>
        /// 是否已付清
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool IsPaid(int orderId)
        {
            Order model = GetInfo(orderId);
            if (model == null)
                return true; //订单号码错误，直接返回true
            if (model.Status == (int) Shop.Status.Payoff || model.MoneyTotal == model.MoneyReceived)
                return true;
            return false;
        }


        /// <summary>
        /// 当订单结清时，赠送相应会员购物积分
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public int AddUserExp(int orderId)
        {
            Order model = GetInfo(orderId);
            if (model == null) return 0;
            try
            {
                UserScore ms = new UserScore
                {
                    OrderId = orderId,
                    UserName = UserManage.Current.UserName,
                    CheckIn = model.PresentExp,
                    Remark = "订单：“" + model.OrderNum + "”结清"
                };


                Result res = new MemberScoreManage().Add(ms);

                if (string.IsNullOrEmpty(res.Errors) == false)
                    return 0;

                return 1;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 更新订单状态.如果是结清订单,将赠送会员积分
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <param name="status">更新后的订单状态</param>
        /// <returns>是否成功</returns>
        public bool UpdateOrderStatus(int orderId, Shop.Status status)
        {
            if (Exists(orderId))
            {
                Order model = GetInfo(orderId);
                model.Status = (int) status;

                Result resu;
                if (status == Shop.Status.Finished)
                {
                    //结清订单时,赠送会员积分
                    resu = Add(model, null);
                    if (string.IsNullOrEmpty(resu.Errors))
                    {
                        AddUserExp(orderId);
                        return true;
                    }
                    return false;
                }
                resu = Add(model, null);
                return string.IsNullOrEmpty(resu.Errors);
            }
            return false;
        }

        /// <summary>
        /// 更新发货状态
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <param name="status">更新后的发货状态</param>
        /// <returns>是否成功</returns>
        public bool UpdateOrderDeliverStatus(int orderId, Shop.DeliverStatus status)
        {
            if (Exists(orderId))
            {
                Order model = GetInfo(orderId);
                model.DeliverStatus = (int) status;

                if (status == Shop.DeliverStatus.SiginIn)
                    model.Status = (int) Shop.Status.Finished;

                Result resu = Add(model, null);
                return string.IsNullOrEmpty(resu.Errors);
            }
            return false;
        }

        /// <summary>
        /// 获取订单状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Shop.Status GetOrderStatus(int orderId)
        {
            if (Exists(orderId))
                return (Shop.Status) GetInfo(orderId).Status;
            return Shop.Status.WaitForConfirm;
        }

        /// <summary>
        /// 获取订单状态描述
        /// </summary>
        /// <param name="status">订单状态</param>
        /// <returns></returns>
        public string GetOrderStatusDescription(Shop.Status status)
        {
            switch (status)
            {
                case Shop.Status.WaitForConfirm:
                    return "等待确认";

                case Shop.Status.Confimed:
                    return "已经确认订单";

                case Shop.Status.ReceivedEarnest:
                    return "已付定金";

                case Shop.Status.Payoff:
                    return "已经付清";
                case Shop.Status.Finished:
                    return "交易成功结束,结清订单";
            }

            return "系统未定义";
        }

        /// <summary>
        /// 获取订单状态描述
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string GetOrderStatusDescription(int orderId)
        {
            if (Exists(orderId))
                return GetOrderStatusDescription(GetOrderStatus(orderId));
            return
                GetOrderStatusDescription((Shop.Status) 99999);
        }

        /// <summary>
        /// 获取订单物流状态
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public Shop.DeliverStatus GetDeliverStatus(int orderId)
        {
            if (Exists(orderId))
                return (Shop.DeliverStatus) GetInfo(orderId).DeliverStatus;

            return Shop.DeliverStatus.Failure;
        }

        /// <summary>
        /// 获取订单物流状态描述
        /// </summary>
        /// <param name="deliverStatus">订单物流状态</param>
        /// <returns></returns>
        public string GetDeliverStatusDescription(Shop.DeliverStatus deliverStatus)
        {
            switch (deliverStatus)
            {
                case Shop.DeliverStatus.WaitForConfirm:
                    return "未开始配送";
                case Shop.DeliverStatus.Preparative:
                    return "配送准备中";

                case Shop.DeliverStatus.GoodsSending:
                    return "已发货";

                case Shop.DeliverStatus.SiginIn:
                    return "已签收";

                case Shop.DeliverStatus.Failure:
                    return "物流失败";
            }

            return "系统未定义";
        }

        /// <summary>
        /// 获取订单物流状态描述
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string GetDeliverStatusDescription(int orderId)
        {
            if (Exists(orderId))
                return GetDeliverStatusDescription(GetDeliverStatus(orderId));

            return GetDeliverStatusDescription(Shop.DeliverStatus.Failure);
        }

        /// <summary>
        /// 获取付款状态
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns></returns>
        public Shop.MoneyReceivedStatus GetMoneyReceivedStatus(int orderId)
        {
            if (!Exists(orderId))
                return Shop.MoneyReceivedStatus.WaitBuyerPay;
            Order model = GetInfo(orderId);
            if (0M >= model.MoneyReceived)
                return Shop.MoneyReceivedStatus.WaitBuyerPay;
            if (model.MoneyTotal > model.MoneyReceived)
                return Shop.MoneyReceivedStatus.ReceivedEarnest;

            return Shop.MoneyReceivedStatus.Payoff;
        }

        /// <summary>
        /// 获取付款状态描述
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public string GetMoneyReceivedStatusDescription(int orderId)
        {
            if (Exists(orderId))
                return GetMoneyReceivedStatusDescription(GetMoneyReceivedStatus(orderId));
            return
                GetMoneyReceivedStatusDescription((Shop.MoneyReceivedStatus) 99999);
        }

        /// <summary>
        /// 获取付款状态描述
        /// </summary>
        /// <param name="moneyReceivedStatus">付款状态</param>
        /// <returns></returns>
        public string GetMoneyReceivedStatusDescription(Shop.MoneyReceivedStatus moneyReceivedStatus)
        {
            switch (moneyReceivedStatus)
            {
                case Shop.MoneyReceivedStatus.WaitBuyerPay:
                    return "等待支付";

                case Shop.MoneyReceivedStatus.ReceivedEarnest:
                    return "已付定金";

                case Shop.MoneyReceivedStatus.Payoff:
                    return "已付清";
            }

            return "系统未定义";
        }

        /// <summary>
        /// 绑定取得的用户的订单
        /// </summary>
        /// <param name="DDL"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        public void GetOrdersWithUserName(DropDownList DDL, string userName)
        {
            DDL.DataSource = MyDAL.GetOrdersWithUserName(userName);
            DDL.DataTextField = "OrderNum";
            DDL.DataValueField = "ID";
            DDL.DataBind();
            DDL.Items.Insert(0, new ListItem("<请选择>", "0"));
        }

        /// <summary>
        /// 合并订单
        /// </summary>
        /// <param name="OrderIdZ">主订单</param>
        /// <param name="OrderIdC">从订单</param>
        public void OrdersMerge(int OrderIdZ, int OrderIdC)
        {
            MyDAL.OrdersMerge(OrderIdZ, OrderIdC);
        }

        /// <summary>
        /// 检查订单是否会超出库存
        /// </summary>
        /// <param name="cartGuid"></param>
        /// <returns></returns>
        public bool CheckOutStock(string cartGuid)
        {
            int[] i = MyDAL.CheckOutStock(cartGuid);

            return i.Any(x => x > 0);
        }
    }
}